const app = getApp()
const util = require("../../utils/utils.js")
// pages/order-lists/orderlist.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isBuying: false,
    orderList: [],
    userNicknames: [],
    orders: [
      //   {
      //   itemid: 'itemid',
      //   imgUrl: "/assets/product_img/pro1.jpg",
      //   title: 'title',
      //   price: '200.00',
      //   state: 'finished',
      //   userinfo: {
      //     username: 'username',
      //     avatarUrl: "/assets/avatars/avatar1.jpg"
      //   }
      // }, {
      //   itemid: 'itemid',
      //   imgUrl: "/assets/product_img/pro1.jpg",
      //   title: 'title',
      //   price: '200.00',
      //   state: 'proceeding',
      //   userinfo: {
      //     username: 'username',
      //     avatarUrl: "/assets/avatars/avatar1.jpg"
      //   }
      // }
    ]

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    this.setData({
      isBuying: app.globalData.isBuying
    })
    if (this.data.isBuying) {
      wx.setNavigationBarTitle({
        title: "购买记录"
      });
      wx.request({
        url: 'http://localhost:8888/buying/getBuyingByUser',
        method: 'GET',
        data: {
          username: app.globalData.loginAccount
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          that.setData({
            orders: res.data.data
          })
          for (var i = 0; i < that.data.orders.length; i++) {
            var iPhoto = "orders[" + i + "].photo"
            that.setData({
              [iPhoto]: util.strToArr(that.data.orders[i].photo)[0],
            })
          }
          for (var i = 0; i < that.data.orders.length; i++) {
            that.getNicknames(that.data.orders[i].username, i)
          }
        }
      })
      wx.request({
        url: 'http://localhost:8888/buying/getBuyingList',
        method: 'GET',
        data: {
          username: app.globalData.loginAccount
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          that.setData({
            orderList: res.data.data
          })
        }
      })
    } else {
      wx.setNavigationBarTitle({
        title: "出售记录"
      });
      wx.request({
        url: 'http://localhost:8888/buying/getSellingByUser',
        method: 'GET',
        data: {
          username: app.globalData.loginAccount
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          that.setData({
            orders: res.data.data
          })
          for (var i = 0; i < that.data.orders.length; i++) {
            var iPhoto = "orders[" + i + "].photo"
            that.setData({
              [iPhoto]: util.strToArr(that.data.orders[i].photo)[0],
            })
          }
        }
      })
      wx.request({
        url: 'http://localhost:8888/buying/getSellingList',
        method: 'GET',
        data: {
          username: app.globalData.loginAccount
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          that.setData({
            orderList: res.data.data
          })
          for (var i = 0; i < that.data.orderList.length; i++) {
            that.getNicknames(that.data.orderList[i].username, i)
          }
        }
      })
    }
  },

  getNicknames(id, i) {
    var that = this
    wx.request({
      url: 'http://localhost:8888/account/getAccount',
      method: 'GET',
      data: {
        id: id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var iNickname = "userNicknames[" + i + "]"
        that.setData({
          [iNickname]: res.data.data.username
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  viewDetail(e) {
    app.globalData.viewBuyingId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../order-detail/detail',
    })
  },
  confirm(e) {
    //console.log("confirm get");
    var that = this
    var index = e.currentTarget.dataset.index
    var id = e.currentTarget.dataset.id
    var status = e.currentTarget.dataset.status
    wx.request({
      url: 'http://localhost:8888/buying/changeStatus',
      method: 'POST',
      data: {
        id: id,
        status: status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        var iStatus = "orderList[" + index + "].status"
        that.setData({
          [iStatus]: status
        })
      }
    })
    var itemname = this.data.orders[index].itemname
    var seller = this.data.orders[index].username
    var buyer = this.data.orderList[index].username
    if(status == "已接受") {
      this.sendSysMsg(buyer, "您的订单（"+itemname+"）卖家已接受，请注意查看")
    }
    if(status == "已拒绝") {
      this.sendSysMsg(buyer, "您的订单（"+itemname+"）卖家已拒绝，请注意查看")
    }
    if(status == "已发货") {
      this.sendSysMsg(buyer, "您的订单（"+itemname+"）卖家已发货，请注意查看")
    }
    if(status == "已完成") {
      this.sendSysMsg(buyer, "您的订单（"+itemname+"）已完成")
      this.sendSysMsg(seller, "您的商品（"+itemname+"）交易已完成")
    }
  },
  sendSysMsg(user, msg) {
    wx.request({
      url: 'http://localhost:8888/chatting/sendMsg',
      method: 'POST',
      data: {
        user1: "sys",
        user2: user,
        content: msg
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
      }
    })
  }
})